const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require('path')

const sfs = require('fs')
const querystring =require('querystring');
const sendToWormhole = require('stream-wormhole');
var formidable = require('formidable');

class CommonController extends Controller {
	// 上传
	async upload() {
		const ctx = this.ctx;

		if (!ctx.request.files) {
			return ctx.apiFail('请先选择上传文件');
		}
		console.log(ctx.request.files)
		const file = ctx.request.files[0];
		// const name = 'egg-oss-demo/' + path.basename(file.filename);
		// 上传路径文件名
		// file.filename文件名，extname后缀名(类似.jpg)
		const name = 'egg-oss-demo/' + ctx.genID(10) + path.extname(file.filename);
		let result;
		try {
			// 文件上传到os中
			result = await ctx.oss.put(name, file.filepath);
		} catch (err) {
			console.log(err);
		} finally {
			await fs.unlink(file.filepath);
		}

		if (result) {
			return ctx.apiSuccess(result.url);
		}

		ctx.apiFail('上传失败');
	}
	
	async uploadLocal(){
		const ctx = this.ctx;
		/* let params_data = await this.parseParams(ctx.req)
		console.log(params_data.fields) */
		    
		let stream = await ctx.getFileStream()
		let filename = Date.now() + stream.filename // stream对象也包含了文件名，大小等基本信息
		// 创建文件写入路径
		let date = new Date()
		let fileDirname = ''+date.getFullYear() + date.getMonth() + date.getDate()
		let target = path.join('./', `uploadfile/${fileDirname}`)
		// 目录不存在就创建
		ctx.mkdirsSync(target)
		target = path.join(target,`/${filename}`)
		const result = await new Promise((resolve, reject) => {
			// 创建文件写入流
			const remoteFileStrem = sfs.createWriteStream(target)
			// 以管道方式写入流
			stream.pipe(remoteFileStrem)
			let errFlag
			// 监听error事件
			remoteFileStrem.on('error', err => {
				errFlag = true
				// 停止写入
				sendToWormhole(stream)
				remoteFileStrem.destroy()
				console.log(err)
				reject(err)
			})
			 
			// 监听写入完成事件
			remoteFileStrem.on('finish', () => {
				if (errFlag) return
				resolve({ filepath:target, filename, name: stream.fields })
			})
		  
		})
		ctx.body = { code: 200, message: 'ok', data: result }
	}
	
	// formdata解析
	async parseParams(req){
		var form = new formidable.IncomingForm();
		return new Promise((resolve, reject) => {
			form.parse(req, (err, fields, files) => {
				resolve({ fields, files });
			});
		});
	}
}

module.exports = CommonController;
